package com.gdufe.product.mq;

import com.gdufe.common.entity.OrderEntity;
import com.gdufe.common.vo.AddPointsVo;
import com.gdufe.common.vo.ReduceStockVo;
import com.gdufe.common.entity.Product;
import com.gdufe.product.service.ProductUserService;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component
@RocketMQMessageListener(nameServer = "${rocketmq.name-server}",topic = "payorder",
        consumerGroup = "mall-product",messageModel = MessageModel.BROADCASTING)
public class ProductMQListener implements RocketMQListener <OrderEntity>{

    @Autowired
    private ProductUserService  productUserService;

    @Resource(type = RocketMQTemplate.class)
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(OrderEntity order) {
        long id=order.getProductId();
        Product product = productUserService.getById(id);
        if (product.getStock() >= order.getProductNum()){
            //若库存足够

            //修改订单状态与设置支付时间
            order.setStatus(1);
            order.setPayTime(new Date());

            //扣减商品库存
            ReduceStockVo vo = new ReduceStockVo(order.getProductId(), order.getProductNum());
            productUserService.reductStock(vo);

            //包装加分vo
            int points = product.getPayPoint();
            AddPointsVo addPointsVo = new AddPointsVo(order.getUserId(), points * order.getProductNum());

            //发送消息给user模块添加用户积分
            rocketMQTemplate.convertAndSend("uppoint",addPointsVo);
        }else {
            //库存不足，修改订单状态
            order.setStatus(2);
            order.setPayResoult(1);
        }
        //发送消息给order模块修改订单状态
        rocketMQTemplate.convertAndSend("changstatus",order);

    }
}
